<script setup>
import {
  getMenu,
  listMenu,
  saveMenu,
  findMaxSort,
  checkMenuNameUnique,
  checkMenuCodeUnique
} from "@/api/system/menu";

const props = defineProps({
  id: {
    type: [Number, String],
    default: ""
  }
});

const formRef = ref();
const data = ref({
  loading: false,
  form: {
    id: props.id
  },
  rules: {
    menuName: [
      { required: true, message: "请输入菜单名称", trigger: "blur" },
      { validator: getcheckMenuNameUnique }
    ],
    menuCode: [
      { required: true, message: "请输入菜单编码", trigger: "blur" },
      { validator: getcheckMenuCodeUnique }
    ],
    menuType: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
    icon: [{ required: true, message: "选择图标", trigger: "blur" }],
    parentId: [{ required: true, message: "选择上级菜单", trigger: "blur" }]
  },

  treeMenuList: []
});

onMounted(() => {
  if (data.value.form.id != "") {
    getInfo();
  } else {
    getfindMaxSort();
  }
  getTreeselect();
});

function getTreeselect() {
  listMenu().then((res) => {
    data.value.treeMenuList = [];
    let menu = { id: "0", label: "主类目", children: [], key: 0 };
    menu.children = getTreeData(res.data);
    data.value.treeMenuList.push(menu);
    console.log("menu", data.value.treeMenuList);
  });
}

function getcheckMenuNameUnique(rule, value, callback) {
  const msg = "菜单名称已存在";
  if (value === "") {
    callback();
  } else {
    const checkData = {
      menuName: value,
      parentId:
        data.value.form.parentId !== undefined ? data.value.form.parentId : "",
      id: data.value.form.id !== undefined ? data.value.form.id : ""
    };
    checkMenuNameUnique(checkData).then((response) => {
      if (response.data.code === "1") {
        callback();
      } else {
        callback(msg);
      }
    });
  }
}

function getcheckMenuCodeUnique(rule, value, callback) {
  const msg = "路由地址已存在";
  if (value === "") {
    callback();
  } else {
    const checkData = {
      menuCode: value,
      id: data.value.form.id !== undefined ? data.value.form.id : ""
    };
    checkMenuCodeUnique(checkData).then((response) => {
      if (response.data.code === "1") {
        callback();
      } else {
        callback(msg);
      }
    });
  }
}
function getTreeData(data) {
  return data.map((tree) => {
    tree.id = tree.id;
    tree.label = tree.menuName;
    if (tree.children) {
      tree.children = getTreeData(tree.children);
    }
    return tree;
  });
}
function getInfo() {
  data.value.loading = true;
  getMenu(props.id).then((res) => {
    data.value.loading = false;
    data.value.form = res.data;
  });
}
function getfindMaxSort() {
  findMaxSort(data.value.form.parentId).then((res) => {
    data.value.form.treeSort = res.data;
  });
}
// 得到节点
function getnode(node, prop, event) {
  console.log("node", node, prop, event);
  data.value.form.parentId = node.id;
}
function handleTree(data, id, parentId, children) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children"
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

defineExpose({
  submit(callback) {
    if (data.value.form.id == "") {
      formRef.value.validate((valid) => {
        if (valid) {
          saveMenu(data.value.form).then(() => {
            ElMessage.success({
              message: "保存成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    } else {
      formRef.value.validate((valid) => {
        if (valid) {
          saveMenu(data.value.form).then(() => {
            ElMessage.success({
              message: "保存成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    }
  }
});
</script>

<template>
  <div v-loading="data.loading">
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="data.rules"
      label-width="120px"
      label-suffix=" "
      label-position="top"
      style="padding: 0 20px"
    >
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input
              v-model="data.form.menuName"
              placeholder="请输入菜单名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单编码" prop="menuCode">
            <el-input
              v-model="data.form.menuCode"
              placeholder="请输入菜单编码"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="菜单类型" prop="menuName">
            <el-radio-group
              v-model="data.form.menuType"
              label="position control"
              :disabled="data.form.id ? true : false"
            >
              <el-radio-button label="M">目录</el-radio-button>
              <el-radio-button label="C">菜单</el-radio-button>
              <el-radio-button label="F">按钮</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图标" prop="menuCode">
            <icon-picker v-model="data.form.icon" />
            {{ data.form.icon }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="上级菜单" prop="parentId">
            <el-tree-select
              v-model="data.form.parentId"
              :data="data.treeMenuList"
              :default-expand-all="true"
              node-key="id"
              @node-click="getnode"
              :check-strictly="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="路由地址" prop="path">
            <el-input v-model="data.form.path" placeholder="请输入路由地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12" v-if="data.form.menuType == 'C'"
          ><el-form-item label="组件路径" prop="component">
            <el-input
              v-model="data.form.component"
              placeholder="请输入组件路径"
            /> </el-form-item
        ></el-col>
        <el-col
          :span="12"
          v-if="data.form.menuType == 'C' || data.form.menuType == 'F'"
          ><el-form-item label="权限标识" prop="perms">
            <el-input
              v-model="data.form.perms"
              placeholder="请输入权限标识"
            /> </el-form-item
        ></el-col>
      </el-row>

      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="排序" prop="treeSort">
            <el-input
              v-model="data.form.treeSort"
              placeholder="请输入排序"
              style="width: 120px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否外链" prop="isFrame">
            <el-radio-group
              v-model="data.form.isFrame"
              label="position control"
            >
              <el-radio-button label="0">是</el-radio-button>
              <el-radio-button label="1">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="是否显示" prop="visible">
            <el-radio-group
              v-model="data.form.visible"
              label="position control"
            >
              <el-radio-button label="0">是</el-radio-button>
              <el-radio-button label="1">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="data.form.status" label="position control">
              <el-radio-button label="0">正常</el-radio-button>
              <el-radio-button label="1">停用</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用平台" prop="type">
            <el-radio-group v-model="data.form.type">
              <el-radio-button label="0">平台</el-radio-button>
              <el-radio-button label="1">商户</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="data.form.remark" type="textarea" rows="3" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
